package com.greensam.server.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.greensam.common.util.PinyinUtil;
import com.greensam.domain.dto.request.LoginRequest;
import com.greensam.domain.dto.request.RegisterRequest;
import com.greensam.domain.entity.BaseUserInfo;
import com.greensam.domain.mapper.UserMapper;
import com.greensam.server.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Author: Machengrui
 * @Date: 2024/9/24 9:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, BaseUserInfo> implements UserService {

    @Override
    public void login(LoginRequest request) {
        String account = request.getAccount();
        BaseUserInfo user = this.lambdaQuery()
                .eq(BaseUserInfo::getAccount, account)
                .eq(BaseUserInfo::getState, 1)
                .one();
        if (user == null) {
            throw new IllegalArgumentException("账号不存在");
        }
        if (!user.getPassword().equals(request.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }
    }

    @Override
    public void register(RegisterRequest request) {
        String account = request.getAccount();
        BaseUserInfo existingUser = this.lambdaQuery()
                .eq(BaseUserInfo::getAccount, account)
                .eq(BaseUserInfo::getState, 1)
                .one();
        if (existingUser != null) {
            throw new IllegalArgumentException("账号已存在");
        }
        BaseUserInfo buildUserInfo = BaseUserInfo.builder()
                .account(account)
                .password(request.getPassword())
                .userName(request.getUserName())
                .code(PinyinUtil.getSimplePinYin(request.getUserName()))
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        this.save(buildUserInfo);
    }
}
